package com.totoro.exception;

import com.totoro.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Niki on 2018/1/19 9:34
 */
@ControllerAdvice //处理所有的Controller的异常
public class GlobalExceptionHandler {



    //返回异常页面，并且添加异常数据
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView handle404Error(HttpServletRequest request, HttpServletResponse response, Exception e){
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", "访问页面异常！");
        mav.setViewName("404");
        return mav;
    }

    //返回ajax异常
    @ExceptionHandler(AjaxException.class)
    @ResponseBody
    public Result<String> ajaxException(HttpServletRequest request, HttpServletResponse response){
        Result<String> result = new Result<String>();
        result.setMsgCode("500");
        result.setMsg("访问接口"+request.getRequestURL().toString()+"异常");
        return result;
    }
}
